<template>
  <div class="p-6">
    <a-row class="mb-6" align="center" justify="space-between">
      <a-col>
        <a-space>
          <h2 class="text-2xl font-bold">房态管理</h2>
          <a-tag>共 {{ totalRooms }} 间房</a-tag>
        </a-space>
      </a-col>
      <a-col>
        <a-space>
          <a-radio-group type="button" v-model="viewMode">
            <a-radio value="floor">楼层视图</a-radio>
            <a-radio value="list">列表视图</a-radio>
          </a-radio-group>
          <a-button type="primary" @click="refreshRoomStatus">
            <template #icon><icon-refresh /></template>
            刷新状态
          </a-button>
        </a-space>
      </a-col>
    </a-row>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="mb-6">
      <a-col :span="6">
        <a-card class="stat-card" :style="{ background: 'var(--color-bg-2)' }">
          <a-statistic
            title="总房间数"
            :value="totalRooms"
            :value-style="{ color: '#165DFF' }"
          >
            <template #prefix>
              <icon-home />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :style="{ background: 'var(--color-bg-2)' }">
          <a-statistic
            title="入住率"
            :value="occupancyRate"
            :precision="2"
            suffix="%"
            :value-style="{ color: '#0FC6C2' }"
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :style="{ background: 'var(--color-bg-2)' }">
          <a-statistic
            title="待清洁"
            :value="dirtyRooms"
            :value-style="{ color: '#FF7D00' }"
          >
            <template #prefix>
              <icon-tool />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :style="{ background: 'var(--color-bg-2)' }">
          <a-statistic
            title="维护中"
            :value="maintenanceRooms"
            :value-style="{ color: '#F53F3F' }"
          >
            <template #prefix>
              <icon-wrench />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 楼层选择和筛选器 -->
    <a-card class="mb-6" :bordered="false">
      <a-row :gutter="16">
        <a-col :span="viewMode === 'floor' ? 24 : 8">
          <a-space direction="vertical" fill>
            <span class="text-sm font-medium">楼层选择</span>
            <a-radio-group
              v-model="currentFloor"
              type="button"
              size="large"
              :style="{ width: '100%' }"
            >
              <a-radio
                v-for="floor in floors"
                :key="floor"
                :value="floor"
                class="floor-radio"
              >
                {{ floor }}层
              </a-radio>
            </a-radio-group>
          </a-space>
        </a-col>
        <template v-if="viewMode === 'list'">
          <a-col :span="8">
            <a-space direction="vertical" fill>
              <span class="text-sm font-medium">房型筛选</span>
              <a-select v-model="filters.roomType" placeholder="全部房型">
                <a-option value="">全部</a-option>
                <a-option
                  v-for="type in roomTypes"
                  :key="type.id"
                  :value="type.id"
                >
                  {{ type.name }}
                </a-option>
              </a-select>
            </a-space>
          </a-col>
          <a-col :span="8">
            <a-space direction="vertical" fill>
              <span class="text-sm font-medium">状态筛选</span>
              <a-select v-model="filters.status" placeholder="全部状态">
                <a-option value="">全部</a-option>
                <a-option value="available">空闲</a-option>
                <a-option value="occupied">已入住</a-option>
                <a-option value="reserved">已预订</a-option>
                <a-option value="maintenance">维护中</a-option>
              </a-select>
            </a-space>
          </a-col>
        </template>
      </a-row>
    </a-card>

    <!-- 房态展示 -->
    <a-card :bordered="false">
      <!-- 楼层视图 -->
      <template v-if="viewMode === 'floor'">
        <div class="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4">
          <a-card
            v-for="room in filteredRooms"
            :key="room.roomNumber"
            :class="[
              'room-card cursor-pointer hover:shadow-lg transition-shadow',
              getRoomStatusClass(room.status),
            ]"
            :bordered="false"
            @click="showRoomDetails(room)"
          >
            <template #title>
              <div class="text-center">
                <div class="font-medium">{{ room.roomNumber }}</div>
                <a-tag size="small" :color="getRoomTypeColor(room.roomType)">
                  {{ room.roomType }}
                </a-tag>
              </div>
            </template>
            <div class="text-center">
              <a-space direction="vertical" :size="2">
                <span class="text-sm">{{
                  getRoomStatusText(room.status)
                }}</span>
                <a-tag
                  size="small"
                  :color="getCleaningStatusColor(room.cleaningStatus)"
                >
                  {{ getCleaningStatusText(room.cleaningStatus) }}
                </a-tag>
                <div
                  v-if="room.status === 'occupied'"
                  class="text-xs text-gray-500"
                >
                  预计退房: {{ formatTime(room.currentGuest?.checkOutTime) }}
                </div>
              </a-space>
            </div>
          </a-card>
        </div>
      </template>

      <!-- 列表视图 -->
      <template v-else>
        <a-table
          :data="filteredRooms"
          :columns="columns"
          :pagination="{ pageSize: 10 }"
          :bordered="false"
          :stripe="true"
          :row-class="getRowClass"
        >
          <template #room="{ record }">
            <a-space>
              <span class="font-medium">{{ record.roomNumber }}</span>
              <a-tag size="small" :color="getRoomTypeColor(record.roomType)">
                {{ record.roomType }}
              </a-tag>
            </a-space>
          </template>
          <template #status="{ record }">
            <a-tag :color="getStatusTagColor(record.status)">
              {{ getRoomStatusText(record.status) }}
            </a-tag>
          </template>
          <template #cleaning="{ record }">
            <a-tag :color="getCleaningStatusColor(record.cleaningStatus)">
              {{ getCleaningStatusText(record.cleaningStatus) }}
            </a-tag>
          </template>
          <template #guest="{ record }">
            <template v-if="record.currentGuest">
              <a-space direction="vertical" :size="2">
                <span>{{ record.currentGuest.name }}</span>
                <span class="text-xs text-gray-500">
                  {{ formatTime(record.currentGuest.checkInTime) }} -
                  {{ formatTime(record.currentGuest.checkOutTime) }}
                </span>
              </a-space>
            </template>
            <span v-else>-</span>
          </template>
          <template #operations="{ record }">
            <a-space>
              <a-button
                type="text"
                size="small"
                @click="showRoomDetails(record)"
              >
                详情
              </a-button>
              <a-button
                v-if="record.cleaningStatus === 'dirty'"
                type="text"
                size="small"
                status="success"
                @click="setCleaningStatus(record, 'cleaned')"
              >
                标记已清洁
              </a-button>
              <a-button
                v-if="record.status !== 'maintenance'"
                type="text"
                size="small"
                status="warning"
                @click="setMaintenance(record)"
              >
                设为维护
              </a-button>
            </a-space>
          </template>
        </a-table>
      </template>

      <!-- 图例说明 -->
      <div class="mt-4 pt-4 border-t border-gray-200">
        <a-space size="large">
          <a-space>
            <div
              class="w-3 h-3 rounded bg-blue-100 border border-blue-500"
            ></div>
            <span class="text-sm">空闲</span>
          </a-space>
          <a-space>
            <div
              class="w-3 h-3 rounded bg-green-100 border border-green-500"
            ></div>
            <span class="text-sm">已入住</span>
          </a-space>
          <a-space>
            <div
              class="w-3 h-3 rounded bg-yellow-100 border border-yellow-500"
            ></div>
            <span class="text-sm">已预订</span>
          </a-space>
          <a-space>
            <div class="w-3 h-3 rounded bg-red-100 border border-red-500"></div>
            <span class="text-sm">维护中</span>
          </a-space>
        </a-space>
      </div>
    </a-card>

    <!-- 房间详情抽屉 -->
    <a-drawer
      :visible="showDetailsDrawer"
      @cancel="showDetailsDrawer = false"
      :width="500"
      :unmount-on-close="false"
      :mask-closable="true"
      :footer="false"
    >
      <template #title>
        <a-space>
          <span>房间详情</span>
          <a-tag :color="getStatusTagColor(selectedRoom?.status)">
            {{ getRoomStatusText(selectedRoom?.status) }}
          </a-tag>
        </a-space>
      </template>

      <template v-if="selectedRoom">
        <a-descriptions :column="2" size="large" :data="roomDetailData" />

        <!-- 当前入住信息 -->
        <template v-if="selectedRoom.status === 'occupied'">
          <a-divider>当前入住信息</a-divider>
          <a-descriptions :column="2" :data="guestDetailData" />
        </template>

        <!-- 维护记录 -->
        <template v-if="selectedRoom.maintenanceRecords?.length">
          <a-divider>维护记录</a-divider>
          <a-timeline>
            <a-timeline-item
              v-for="record in selectedRoom.maintenanceRecords"
              :key="record.id"
              :dot-color="record.status === 'completed' ? 'green' : 'blue'"
            >
              <div class="flex justify-between">
                <span>{{ record.type }}</span>
                <span class="text-gray-500">{{ record.date }}</span>
              </div>
              <p class="text-gray-600 mt-1">{{ record.description }}</p>
            </a-timeline-item>
          </a-timeline>
        </template>

        <!-- 操作按钮 -->
        <div class="absolute bottom-0 left-0 right-0 p-4 bg-white border-t">
          <a-space>
            <a-button
              v-if="selectedRoom.status !== 'maintenance'"
              status="warning"
              @click="setMaintenance(selectedRoom)"
            >
              设为维护
            </a-button>
            <a-button
              v-if="selectedRoom.cleaningStatus !== 'cleaned'"
              type="primary"
              @click="setCleaningStatus(selectedRoom, 'cleaned')"
            >
              标记已清洁
            </a-button>
            <a-button
              v-if="selectedRoom.cleaningStatus === 'cleaned'"
              @click="setCleaningStatus(selectedRoom, 'dirty')"
            >
              标记待清洁
            </a-button>
          </a-space>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import {
  IconHome,
  IconUser,
  IconTool,
  IconWrench,
  IconRefresh,
} from "@arco-design/web-vue/es/icon";

// 视图模式
const viewMode = ref("floor");

// 楼层和筛选
const currentFloor = ref(1);
const floors = [1, 2, 3, 4, 5, 6];
const filters = ref({
  roomType: "",
  status: "",
});

// 房型数据
const roomTypes = [
  { id: 1, name: "标准单人房" },
  { id: 2, name: "标准双人房" },
  { id: 3, name: "豪华大床房" },
  { id: 4, name: "豪华套房" },
];

// 房间数据
const rooms = ref([
  {
    roomNumber: "101",
    roomType: "标准大床房",
    floor: 1,
    status: "available",
    cleaningStatus: "cleaned",
    price: 288,
  },
  {
    roomNumber: "102",
    roomType: "豪华套房",
    floor: 1,
    status: "occupied",
    cleaningStatus: "cleaned",
    price: 888,
    currentGuest: {
      name: "张三",
      phone: "13800138000",
      checkInTime: "2024-02-27 14:00",
      checkOutTime: "2024-02-28 12:00",
      idCard: "110101199001011234",
    },
  },
  {
    roomNumber: "103",
    roomType: "标准双床房",
    floor: 1,
    status: "maintenance",
    cleaningStatus: "dirty",
    price: 388,
    maintenanceRecords: [
      {
        id: 1,
        type: "设备维修",
        date: "2024-02-27",
        description: "空调故障维修",
        status: "completed",
      },
    ],
  },
  // 更多房间数据...
]);

// 表格列定义
const columns = [
  {
    title: "房间信息",
    slotName: "room",
  },
  {
    title: "状态",
    slotName: "status",
  },
  {
    title: "清洁状态",
    slotName: "cleaning",
  },
  {
    title: "当前客人",
    slotName: "guest",
  },
  {
    title: "操作",
    slotName: "operations",
    width: 200,
  },
];

// 计算属性
const filteredRooms = computed(() => {
  return rooms.value.filter((room) => {
    if (viewMode.value === "floor" && room.floor !== currentFloor.value)
      return false;
    if (filters.value.roomType && room.roomType !== filters.value.roomType)
      return false;
    if (filters.value.status && room.status !== filters.value.status)
      return false;
    return true;
  });
});

const totalRooms = computed(() => rooms.value.length);
const occupancyRate = computed(() => {
  const occupied = rooms.value.filter(
    (room) => room.status === "occupied",
  ).length;
  return ((occupied / totalRooms.value) * 100).toFixed(2);
});
const dirtyRooms = computed(
  () => rooms.value.filter((room) => room.cleaningStatus === "dirty").length,
);
const maintenanceRooms = computed(
  () => rooms.value.filter((room) => room.status === "maintenance").length,
);

// 详情抽屉控制
const showDetailsDrawer = ref(false);
const selectedRoom = ref(null);

// 房间详情数据
const roomDetailData = computed(() => {
  if (!selectedRoom.value) return [];
  return [
    {
      label: "房间号",
      value: selectedRoom.value.roomNumber,
    },
    {
      label: "房型",
      value: selectedRoom.value.roomType,
    },
    {
      label: "楼层",
      value: `${selectedRoom.value.floor}层`,
    },
    {
      label: "价格",
      value: `¥${selectedRoom.value.price}/晚`,
    },
    {
      label: "状态",
      value: getRoomStatusText(selectedRoom.value.status),
    },
    {
      label: "清洁状态",
      value: getCleaningStatusText(selectedRoom.value.cleaningStatus),
    },
  ];
});

const guestDetailData = computed(() => {
  if (!selectedRoom.value?.currentGuest) return [];
  const guest = selectedRoom.value.currentGuest;
  return [
    {
      label: "客人姓名",
      value: guest.name,
    },
    {
      label: "联系电话",
      value: guest.phone,
    },
    {
      label: "身份证号",
      value: guest.idCard,
    },
    {
      label: "入住时间",
      value: formatTime(guest.checkInTime),
    },
    {
      label: "预计退房",
      value: formatTime(guest.checkOutTime),
    },
  ];
});

// 方法
const getRoomStatusClass = (status) => {
  return {
    available: "bg-blue-50 border-blue-200",
    occupied: "bg-green-50 border-green-200",
    reserved: "bg-yellow-50 border-yellow-200",
    maintenance: "bg-red-50 border-red-200",
  }[status];
};

const getRoomStatusText = (status) => {
  return {
    available: "空闲",
    occupied: "已入住",
    reserved: "已预订",
    maintenance: "维护中",
  }[status];
};

const getStatusTagColor = (status) => {
  return {
    available: "blue",
    occupied: "green",
    reserved: "orange",
    maintenance: "red",
  }[status];
};

const getRoomTypeColor = (type) => {
  return (
    {
      标准单人房: "gray",
      标准双人房: "arcoblue",
      豪华大床房: "purple",
      豪华套房: "magenta",
    }[type] || "blue"
  );
};

const getCleaningStatusColor = (status) => {
  return status === "cleaned" ? "green" : "orange";
};

const getCleaningStatusText = (status) => {
  return status === "cleaned" ? "已清洁" : "待清洁";
};

const formatTime = (time) => {
  return dayjs(time).format("MM-DD HH:mm");
};

const showRoomDetails = (room) => {
  selectedRoom.value = room;
  showDetailsDrawer.value = true;
};

const refreshRoomStatus = async () => {
  Message.success("房态数据已更新");
};

const setMaintenance = async (room) => {
  if (await Message.confirm("确定要将该房间设为维护状态吗？")) {
    room.status = "maintenance";
    Message.success("已设置为维护状态");
    showDetailsDrawer.value = false;
  }
};

const setCleaningStatus = async (room, status) => {
  room.cleaningStatus = status;
  Message.success(`已标记为${getCleaningStatusText(status)}`);
  showDetailsDrawer.value = false;
};

const getRowClass = (record) => {
  return {
    "bg-red-50": record.status === "maintenance",
    "bg-yellow-50": record.cleaningStatus === "dirty",
  };
};
</script>

<style lang="scss" scoped>
.stat-card {
  @apply transition-all duration-300;
  &:hover {
    @apply shadow-md transform -translate-y-1;
  }
}

.room-card {
  @apply transition-all duration-300;
  &:hover {
    @apply transform -translate-y-1;
  }
}

.floor-radio {
  @apply flex-1 text-center;
}

:deep(.arco-radio-button) {
  @apply flex-1;
}

:deep(.arco-drawer-footer) {
  @apply border-t border-gray-200;
}
</style>
